<template>
  <div>
    <el-tabs
      v-model="tabIdx"
      type="card"
      tab-position="top"
      @tab-change="handleTab"
    >
      <el-tab-pane
        v-for="(item, index) in chartsArr"
        :key="index"
        :label="item.title"
        :name="index"
      >
      </el-tab-pane>
    </el-tabs>

    <div id="main">渲染图表</div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import bar from "./options/bar";
import pie from "./options/pie";
import { chartGet } from "@/api/product";
export default {
  data() {
    return {
      chartsArr: [
        {
          title: "柱状图",
          options: bar,
        },
        {
          title: "饼状图",
          options: pie,
        },
      ],
      tabIdx: 0,
    };
  },
  mounted() {
    // 基于准备好的dom，初始化echarts实例
    this.myChart = echarts.init(document.getElementById("main"));
    // 绘制柱状图表
    // myChart.setOption(bar);
    // 绘制饼状图
    this.myChart.setOption(bar);

    //请求饼状图在线数据
    chartGet().then((res) => {
      console.log(res);
      let { cateCount } = res.data.results[0];
      this.chartsArr[1].options.series[0].data = cateCount;
    });
  },
  methods: {
    handleTab(idx) {
      console.log(idx, this.tabIdx);
      this.myChart.setOption(this.chartsArr[idx].options); //只能通过setOption改变图表的渲染内容
    },
  },
};
</script>

<style lang="scss" scoped>
#main {
  height: 600px;
  border: 1px solid red;
}
</style>
